import { AnyAction, Reducer } from 'redux';
import { EffectsCommandMap } from 'dva';
import {
  queryRechargeDetail,
  queryPartnersList,
  queryGardenList,
} from './service';

import { RechargeDetailItem } from './data';

import { fetchValidation } from '@/utils';

export interface StateType {
  detailInfo: RechargeDetailItem;
  gardenList: any;
  partnersList: any;
}

export type Effect = (
  action: AnyAction,
  effects: EffectsCommandMap & {
    select: <T>(func: (state: StateType) => T) => T;
  }
) => void;

export interface ModelType {
  namespace: string;
  state: StateType;
  effects: {
    fetch: Effect;
    partners: Effect;
    garden: Effect;
  };
  reducers: {
    save: Reducer;
    initPartners: Reducer;
    initGarden: Reducer;
  };
}

const Model: ModelType = {
  namespace: 'rechargeDetail',

  state: {
    detailInfo: {
      list: [],
      chart: [],
    },
    gardenList: [],
    partnersList: [],
  },

  effects: {
    * fetch({ payload }, { call, put }) {
      const response = yield call(queryRechargeDetail, payload);
      const data = fetchValidation(response);
      yield data && put({
        type: 'save',
        payload: response.body,
      });
    },

    * partners({ payload }, { call, put }) {
      payload = {
        pageIndex: 1,
        pageSize: 20,
        ...payload,
      };
      const response = yield call(queryPartnersList, payload);
      const data = fetchValidation(response);
      yield data && put({
        type: 'initPartners',
        payload: response.body ? response.body.list : [],
      });
    },

    * garden({ payload }, { call, put }) {
      const response = yield call(queryGardenList, payload);
      const data = fetchValidation(response);
      yield data && put({
        type: 'initGarden',
        payload: response.body,
      });
    },
  },

  reducers: {
    save(state, action) {
      return {
        ...state,
        detailInfo: action.payload,
      };
    },

    initPartners(state, action) {
      return {
        ...state,
        partnersList: action.payload,
      };
    },

    initGarden(state, action) {
      return {
        ...state,
        gardenList: action.payload,
      };
    },
  },
};

export default Model;
